<?php

namespace App\Services\Api;

use App\Models\DiscountOrder;
use App\Models\UserRank;
use App\Models\UserCoupon;
use App\Models\BodyWeight;
use App\Models\UserSubscribe;
use App\Models\UserVip;
use Illuminate\Database\Eloquent\Model;

class UserServices
{
    /**
     * @param $user_id
     * @param $UserModel \App\Models\User
     */
    public function user_info($user_id, $UserModel)
    {
        $data = $UserModel->WhereId($user_id)->first();
        /* if($data->expire_time <= date("Y-m-d H:i:s")){
             $data->total_integral = '过期';
         }*/
        $rank = UserRank::where('id', $data->user_rank_id)->first();
        $data->rank_level_name = !empty($rank->rank_name) ? $rank->rank_name : '暫無等級';
        $data->rank_cove = !empty($rank->cove) ? $rank->cove : '';

        $param['user_id'] = auth('api')->user()->id;
        $param['type'] = 1;
        $param['status'] = 1;
        $param['is_expired'] = 1;

        //现金卷
        $data->coupon_number = CouponServices::my_user_coupon($param)->count('*');

        //vip
        $vip = UserVip::where('user_id', $user_id)->where('vip_maturity', ">=", date("Y-m-d H:i:s"))->select('vip_title', 'vip_maturity', 'activate', 'vip_id')->get();

        $vip_array = array();

        //獲取器統一去了 00:00:00 所以這裏要循環修改
        foreach ($vip as &$v) {
            $input_value['vip_title'] = $v->vip_title;
            $input_value['vip_maturity'] = $v->vip_maturity;
            if(!empty($v->activate)){
                $input_value['activate'] = $v->activate." 00:00:00";
            }else{
                $input_value['activate'] = "";
            }
            $input_value['vip_id'] = $v->vip_id;

            $vip_array[] = $input_value;
        }

        $data->vip = $vip_array;

        return $data;
    }

    public function body_weight_add()
    {
        $where[] = ['created_at', ">=", date("Y-m-d 00:00:00", time())];
        $where[] = ['created_at', "<=", date("Y-m-d 23:59:59", time())];
        $count = (new BodyWeight())->where($where)->count('*');

        if (!empty($count)) throw new \Exception('每天只能录一次');

        $input['year_month'] = date("Y-m", time());
        $input['year'] = date("Y", time());
        $input['created_at'] = date("Y-m-d H:i:s", time());
        $input['body_weight'] = request()->body_weight ?? 0;
        $input['user_id'] = auth()->user('api')->id;

        (new BodyWeight())->insert($input);
    }

    public function body_weight_lists()
    {
        $date_type = request()->date_type;

        $where = [];
        $where[] = ['user_id', auth()->user('api')->id];
        switch ($date_type) {
            case 'year':

                if (empty(request()->date_value)) throw new \Exception('请传date_value');

                $where[] = ['year', request()->date_value];

                break;
            case 'year_month':

                if (empty(request()->date_value)) throw new \Exception('请传date_value');

                $where[] = ['year_month', request()->date_value];

                break;
            default:
                break;
        }

        $reault = [
            'user' => auth()->user('api')->head_img,
            'lists' => BodyWeight::where($where)->select('body_weight', 'created_at')->paginate(20),
        ];

        return $reault;
    }

    //我的优惠卷
    public function coupon()
    {
        $input = request()->all();

        if (empty($input['is_expired'])) $input['is_expired'] = 'all';

        $discount_result = (new DiscountOrder());

        //查询是否对应课程
        if (!empty($input['class_base_info_id'])) {
            $discount_result = $discount_result->whereHas('user_counpon', function ($q) use ($input) {
                $q->where('status', 1)->where('class_base_info_id', $input['class_base_info_id']);
            });
        }

        if (!empty($input['status'])) {
            if ($input['status'] == '1') {
                $discount_result = $discount_result->where('is_use_finish', '1');
            } else {
                $discount_result = $discount_result->where('is_use_finish', '2');
            }
        }

        $discount_result = $discount_result->where('user_id', auth()->user('api')->id);

        switch ($input['is_expired']) {
            case '1':
                $discount_result = $discount_result->where('discount_expired', '>=', date('Y-m-d H:i:s', time()));
                break;
            case '2':
                $discount_result = $discount_result->where('discount_expired', '<=', date('Y-m-d H:i:s', time()));
                break;
        }

        $discount_order_id = $discount_result->pluck('id')->toArray();

        $discount_result = $discount_result->select('id', 'discount_title', 'discount_cove', 'discount_expired')
            ->orderBy('id', 'desc')
            ->paginate(15);

        $user_counpon = (new UserCoupon())->whereIn('discount_order_id', $discount_order_id)->get();

        $discount_user_counpon = [];

        //计算已使用的百分比
        foreach ($user_counpon as $v) {
            if (empty($v->discount_order_id)) continue;
            if (!isset($input[$v->discount_order_id]['used'])) $input[$v->discount_order_id]['used'] = 0;
            if (!isset($input[$v->discount_order_id]['total'])) $input[$v->discount_order_id]['total'] = 0;

            if ($v->status == 2) $input[$v->discount_order_id]['used']++;
            $input[$v->discount_order_id]['total']++;

            $discount_user_counpon[$v->discount_order_id] = "{$input[$v->discount_order_id]['used']}/{$input[$v->discount_order_id]['total']}";
        }

        foreach ($discount_result as $v) {
            if (strtotime("{$v->discount_expired}") < time()) {
                $v->is_expired = 1;
            } else {
                $v->is_expired = 0;
            }

            $v->discount_user_counpon = $discount_user_counpon[$v->id] ?? '';
        }

        return $discount_result;
    }

    public function coupon_info()
    {
        $input = request()->all();

        if (empty($input['id'])) throw new \Exception('请传id');
        if (empty($input['status'])) $input['status'] = 0;

        $user_coupon = UserCoupon::with(['class_base_info' => function ($q) {
            $q->with(['class_base' => function ($q) {
                $q->select('id', 'class_name');
            }])->select('id', 'class_base_id', 'class_week', 'class_time');
        }]);

        switch ($input['status']) {
            case '1':
                $user_coupon = $user_coupon->where('status', '1');
                break;
            case '2':
                $user_coupon = $user_coupon->where('status', '2');
                break;
        }

        $user_coupon = $user_coupon->where('user_id', auth()->user('api')->id)
            ->where('discount_order_id', $input['id'])
            ->select('id', 'class_base_info_id', 'status', 'updated_at')
            ->get()
            ->toArray();

        $list = [];

        $user_subscribe_sql = (new UserSubscribe())->where('discount_order_id', $input['id'])->get()->toArray();

        $user_subscribe_result = [];

        foreach ($user_subscribe_sql as $v) {
            $user_subscribe_result[$v['class_base_info_id']] = $v['class_time'];
        }

        foreach ($user_coupon as $v) {
            $user_coupon_input = [];
            $user_coupon_input['class_week'] = $v['class_base_info']['class_week'];
            $user_coupon_input['class_time'] = $user_subscribe_result[$v['class_base_info_id']] ?? '';
            $user_coupon_input['class_name'] = $v['class_base_info']['class_base']['class_name'];
            $user_coupon_input['status'] = $v['status'];
            $user_coupon_input['updated_at'] = $v['updated_at'] ?? '';


            $list[] = $user_coupon_input;
        }

        //查询
        $discount_title = (new DiscountOrder())->where('id', $input['id'])->value('discount_title');

        $result = [
            'list' => $list,
            'discount_title' => $discount_title
        ];

        return $result;
    }
}
